package cn.com.cifi.mars.service.impl;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import cn.com.cifi.mars.bean.dto.ApprovedRecordViewDto;
import cn.com.cifi.mars.bean.vo.price.ApprovedRecordViewVO;
import cn.com.cifi.mars.bean.vo.price.ApprovedViewVO;
import cn.com.cifi.mars.constant.ApprovedStateNameCodeEnum;
import cn.com.cifi.mars.constant.IsDeleteEnum;
import cn.com.cifi.mars.entity.ApprovalBill;
import cn.com.cifi.mars.entity.common.IdmUser;
import cn.com.cifi.mars.mapper.mars.ApprovalBillMapper;
import cn.com.cifi.mars.service.ApprovedRecoreViewService;
import cn.com.cifi.mars.service.IdmUserService;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@Service
public class ApprovedRecoreViewServiceImpl extends ServiceImpl<ApprovalBillMapper,ApprovalBill> implements ApprovedRecoreViewService {
   
    @Autowired
    ApprovalBillMapper approvalBillMapper;
    
    @Autowired
    IdmUserService idmUserService;

    @Value("${previewUrl}")
    String url;

    @Value("${view_approved_url}")
    String view_approved_url;
    
    @Override
    public ApprovedRecordViewVO selectRecordById(String projectId, String searchStr, IdmUser user, String current, String pageSize,String businessType) {
        ApprovedRecordViewVO recordVo = new ApprovedRecordViewVO();
        List<ApprovedRecordViewDto> recordList = new ArrayList<>();
        Page<ApprovedRecordViewDto> pageDto=new Page<>();
        //参数当前页
        pageDto.setCurrent(Integer.parseInt(current));
        //参数每页数量
        pageDto.setSize(Integer.parseInt(pageSize));
        List<ApprovalBill> billList = approvalBillMapper.selectRecordById(pageDto,projectId,searchStr,businessType);
        String alias = user.getAlias();
        if (CollectionUtils.isNotEmpty(billList)){
            for (ApprovalBill approvalBill : billList) {
                ApprovedRecordViewDto recordDto = new ApprovedRecordViewDto();
                String account = approvalBill.getAccount();
                //查询user数据
                IdmUser idmUser = idmUserService.getByAlias(account);
                if (null != idmUser){
                    recordDto.setUsercn(idmUser.getUsercn());
                }
                recordDto.setBusinessKey(approvalBill.getId());
                recordDto.setAccount(account);
                recordDto.setInstanceId(approvalBill.getInstanceId());
                if (alias.equals(account)){
                    recordDto.setIsInitiator(true);
                }else {
                    recordDto.setIsInitiator(false);
                }
                recordDto.setSubject(approvalBill.getSubject());
                recordDto.setCreatedTime(approvalBill.getCreatedTime());
                recordDto.setUpdateTime(approvalBill.getUpdateTime());
                String stateName = ApprovedStateNameCodeEnum.getValueByKey(approvalBill.getState());
                recordDto.setState(stateName.trim());
                if (null != user){
                    ApprovedViewVO vo = getResultUrl(approvalBill, user.getAlias());
                    recordDto.setResUrl(vo.getUrl());
                }
                recordDto.setSuperviseUrl(approvalBill.getSuperviseUrl());
                recordList.add(recordDto);
            }
            recordVo.setList(recordList);
            recordVo.setCurrent(pageDto.getCurrent());
            recordVo.setPages(pageDto.getPages());
            recordVo.setPageSize(pageDto.getSize());
            recordVo.setTotal(pageDto.getTotal());
        }
        return recordVo;
    }

    /**
     * 查看审批
     */
    @Override
    public ApprovedViewVO getResultUrl(ApprovalBill approvalBill, String alias) {
        log.info("getResultUrl:viewApprovedUrl->"+view_approved_url);
        ApprovedViewVO vo = new ApprovedViewVO();
        String instId = approvalBill.getInstanceId();
        String taskId = approvalBill.getTaskId();
        //首次发起
        JSONObject instObject = new JSONObject();
        instObject.put("proInstId",instId);
        //再次发起（驳回/撤回）
        JSONObject instObjectAgain = new JSONObject();
        instObjectAgain.put("proInstId",instId);
        instObjectAgain.put("taskId",taskId);
        //base加密
        String encode = null;
        String encodeAgain = null;
        try {
            encode = Base64.getEncoder().encodeToString(instObject.toString().getBytes("utf-8"));
            encodeAgain = Base64.getEncoder().encodeToString(instObjectAgain.toString().getBytes("utf-8"));
            log.info("getResultUrl:encode->"+encode);
            log.info("getResultUrl:encodeAgain->"+encodeAgain);
        } catch (UnsupportedEncodingException e) {
            log.error("###### errorMsg: ", e);
        }
        //是否跳转 1 跳转 0不跳转
        vo.setStatus(IsDeleteEnum.YES.getKey()+"");
        vo.setUrl(view_approved_url+encode);
        return vo;
    }

    @Override
    public ApprovalBill selectByInstId(String instanceId) {
        QueryWrapper<ApprovalBill> billWrapper = new QueryWrapper<>();
        billWrapper.eq("instance_id",instanceId);
        return approvalBillMapper.selectOne(billWrapper);
    }

    @Override
    public ApprovalBill selectBillByVersionId(String versionId) {
        return approvalBillMapper.selectBillByVersionId(versionId);
    }

}
